/*
 * Copyright (c) 2015_ For Intelligent Group_
 */

package com.intelligent.ispc.common.utils;

import java.io.File;
import java.io.IOException;

/**
 * Created by Peter on 2016/3/15.
 */
public class FileUtils {

    /**
     * Delete file with the path provided.
     *
     * @param sPath file path.
     * @return true if removed.
     */
    public static boolean deleteFile(String sPath) {
        boolean flag = false;
        File file = new File(sPath);
        if (file.isFile() && file.exists()) {
            file.delete();
            flag = true;
        }

        return flag;
    }

    /**
     * Delete more files with the path provided.
     *
     * @param path file path array.
     * @return true if removed.
     */
    public static boolean deleteFile(String[] path) {
        boolean flag = false;
        for (String key : path) {
            flag = deleteFile(key);
        }
        return flag;
    }

    /**
     * Create file with the path provided.
     *
     * @param sPath file path.
     * @return true if success.
     */
    public static boolean createFile(String sPath) {
        boolean flag = false;
        File file = new File(sPath);
        if (!file.exists() && !file.isDirectory()) {
            file.mkdir();
            flag = true;

        }
        return flag;
    }

    /**
     * Create file with the path provided, the parent folder will be create when it cannot be find.
     *
     * @param filePath file path.
     */
    public static void createParentPath(String filePath) {
        File file = new File(filePath);
        if (!file.exists() && !file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
    }

    /**
     * Create file
     *
     * @param filePath file path.
     */
    public static void createSpecificFile(String filePath) {
        File file = new File(filePath);
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * Create folder with the path provided.
     *
     * @param dirPath path.
     */
    public static void createDir(String dirPath) {
        File file = new File(dirPath);
        if (!file.exists()) {
            file.mkdirs();
        }
    }

    /**
     * Delete folder with the path provided.
     *
     * @param dir path.
     */
    public static void deleteDir(String dir) {
        File dirFile = new File(dir);
        File[] childFiles = dirFile.listFiles();
        if (childFiles != null) {
            for (File file : childFiles) {
                if (file.isDirectory()) {
                    deleteDir(file.getPath());
                    file.delete();
                } else {
                    file.delete();
                }
            }
        }
    }
}
